//
// connection.hpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef HTTP_SERVER2_CONNECTION_HPP
#define HTTP_SERVER2_CONNECTION_HPP

#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "reply.hpp"
#include "request.hpp"
#include "request_handler.hpp"
#include "request_parser.hpp"
#include "lua_interface.hpp"

#define __DEFAULT_CONNECTION_TIMEOUT 10 // (seconds)

namespace http {
    namespace server3 {

        /// Represents a single connection from a client.
        class connection
            : public boost::enable_shared_from_this<connection>,
            private boost::noncopyable
        {
        public:
            /// Construct a connection with the given io_service.
            explicit connection(boost::asio::io_service& io_service, request_handler& handler);

            /// Get the socket associated with the connection.
            boost::asio::ip::tcp::socket& socket();

            //for statistics
            static int connection_num;
            static int request_num;

            /// Start the first asynchronous operation for the connection.
            void start();
            void stop();
            ~connection();

        private:
            /// Handle completion of a read operation.
            void handle_read(const boost::system::error_code& e, std::size_t bytes_transferred);

            /// Handle completion of a write operation.
            void handle_write(const boost::system::error_code& e);

            /// Handle for stop connection.
            void handle_stop(const boost::system::error_code& e);

            void reset_new_request();

            /// Socket for the connection.
            boost::asio::ip::tcp::socket socket_;
            boost::asio::strand strand_;

            /// The handler used to process the incoming request.
            request_handler& request_handler_;

            /// Buffer for incoming data.
            boost::array<char, 8192> buffer_;

            /// The incoming request.
            boost::shared_ptr<request> request_ptr_;

            boost::shared_ptr<reply> reply_ptr_;

            /// The parser for the incoming request.
            request_parser request_parser_;

            int time_out; // connection timeout in second

            /// timer for ending connection after timeout.
            boost::asio::deadline_timer timer_;

            int port;
            std::string ip;
        };

        typedef boost::shared_ptr<connection> connection_ptr;

    } // namespace server2
} // namespace http

#endif // HTTP_SERVER2_CONNECTION_HPP
